package com.ruyuan.seckilling.order.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.dependency.order.api.OrderApi;
import com.ruyuan.dependency.order.vo.CreateOrderReuqest;
import com.ruyuan.seckilling.common.CacheKey;
import com.ruyuan.seckilling.common.FileNameUtils;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.OrderCreateMessage;
import com.ruyuan.starter.jedis.CacheSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.Semaphore;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = QueueKey.QUEUE_CREATE_ORDER, consumerGroup = "createOrderGroup")
public class CreateOrderListener implements RocketMQListener<String> {
    private static final Semaphore SEMAPHORE = new Semaphore(500);

    @Autowired
    private CacheSupport cacheSupport;

    @Autowired
    private OrderApi orderApi;

    @Override
    public void onMessage(String messageString) {
        SEMAPHORE.acquireUninterruptibly();
        try {
            handleMessage(messageString);
        } finally {
            SEMAPHORE.release();
        }
    }

    private void handleMessage(String messageString) {
        log.info("收到创建秒杀订单的消息，message={}", messageString);

        OrderCreateMessage message = JSON.parseObject(messageString, OrderCreateMessage.class);
        Long sequence = message.getSequence();
        Long activityId = message.getActivityId();
        Long userId = message.getUserId();
        Long skuId = message.getSkuId();
        Integer count = message.getCount();

        // 幂等控制，避免重复消费
        String key = CacheKey.buildConsumeCreateOrderKey(sequence, activityId, userId, skuId);
        if (cacheSupport.exists(key)) {
            return;
        } else {
            cacheSupport.expire(key, 7200);
        }

        CreateOrderReuqest request = CreateOrderReuqest.builder().sequence(sequence)
                .activityId(activityId).userId(userId).skuId(skuId).count(count).build();
        if (orderApi.ceateOrder(request)) {
            log.info("调用依赖的订单系统创建秒杀订单");
        } else {
            throw new RuntimeException("创建订单失败");
        }
    }
}
